﻿//Copyright (c) 2014, Peter William Dongan
//All rights reserved.
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//* Neither the name of Peter William Dongan nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  


using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace RichTextEditor
{
    /// <summary>
    /// Based on RichTextBox. Allows formatting to be applied to selected text, and for formatting to be applied on the fly before text is typed.
    /// </summary>
    public class RichTextEditor : RichTextBox, INotifyPropertyChanged
    {
        /// <summary>
        /// Creates a new instance of RichTextEditor.
        /// </summary>
        public RichTextEditor()
        {
             DefaultStyleKey = typeof(RichTextBox);
             SelectionChanged += new RoutedEventHandler(RichTextEditor_SelectionChanged);
             GetsFocusAfterFormattingChange = true;
        }

        /// <summary>
        /// Gets or sets a value that indicates whether focus is set to the RichTextEditor after formatting is changed. True by default. If set, the focus will return to the control after any of the IsBoldSelected, IsItalicSelected, IsUnderlinedSelected properties are changed.
        /// </summary>
        public bool GetsFocusAfterFormattingChange { get; set; }
 

        void RichTextEditor_SelectionChanged(object sender, RoutedEventArgs e)
        {
            //NotifyPropertyChanged("IsBoldSelected");
            if (Selection.Start.Parent.GetType().ToString() == "System.Windows.Documents.Run")
            {
                if (((Run)Selection.Start.Parent).FontWeight == FontWeights.Bold)
                    _isBoldSelected = true;
                else
                    _isBoldSelected = false;
                if (((Run)Selection.Start.Parent).FontStyle == FontStyles.Italic)
                   _isItalicSelected = true;
                else
                    _isItalicSelected = false;
                if (((Run)Selection.Start.Parent).GetValue(Run.TextDecorationsProperty) == TextDecorations.Underline)
                    _isUnderlinedSelected = true;
                else
                    _isUnderlinedSelected = false;
                _fontColourSelectedHexString = ((Brush)((Run)Selection.Start.Parent).GetValue(Run.ForegroundProperty)).GetValue(SolidColorBrush.ColorProperty).ToString();
                _fontSizeSelected = (double)((Run)Selection.Start.Parent).GetValue(Run.FontSizeProperty);
                _fontFamilySelected = (FontFamily)((Run)Selection.Start.Parent).GetValue(Run.FontFamilyProperty);
                NotifyPropertyChanged("IsBoldSelected");
                NotifyPropertyChanged("IsItalicSelected");
                NotifyPropertyChanged("IsUnderlinedSelected");
                NotifyPropertyChanged("FontColourSelectedHexString");
                NotifyPropertyChanged("FontSizeSelected");
                NotifyPropertyChanged("FontFamilySelected");
            }
        }

        

        bool _isBoldSelected, _isItalicSelected, _isUnderlinedSelected;
        string _fontColourSelectedHexString;

        /// <summary>
        /// Gets or sets a value that indicates whether selected text is bold or normal. If no text is selected, then it applies the formatting to the next text typed.
        /// </summary>
        public bool IsBoldSelected
        {
            get
            {
                return _isBoldSelected;
            }
            set
            {
                if (value && Selection.Start.Parent.GetType().ToString() == "System.Windows.Documents.Run")
                {
                    Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Bold);
                }
                else
                {
                    Selection.ApplyPropertyValue(Run.FontWeightProperty, FontWeights.Normal);
                }
                _isBoldSelected = value;
                if(GetsFocusAfterFormattingChange)
                    this.Focus();
            }
        }

        /// <summary>
        /// Gets or sets a value that indicates whether selected text is italic or normal. If no text is selected, then it applies the formatting to the next text typed.
        /// </summary>
        public bool IsItalicSelected
        {
            get
            {
                return _isItalicSelected;

            }
            set
            {
                if (value && Selection.Start.Parent.GetType().ToString() == "System.Windows.Documents.Run")
                    Selection.ApplyPropertyValue(Run.FontStyleProperty, FontStyles.Italic);
                else
                    Selection.ApplyPropertyValue(Run.FontStyleProperty, FontStyles.Normal);
                _isItalicSelected = value;
                if (GetsFocusAfterFormattingChange)
                    this.Focus();
            }
        }

        /// <summary>
        /// Gets or sets a value that indicates whether selected text is underlined or not. If no text is selected, then it applies the formatting to the next text typed.
        /// </summary>
        public bool IsUnderlinedSelected
        {
            get
            {
                return _isUnderlinedSelected;

            }
            set
            {
                if (value && Selection.Start.Parent.GetType().ToString() == "System.Windows.Documents.Run")
                    Selection.ApplyPropertyValue(Run.TextDecorationsProperty, TextDecorations.Underline);
                else
                    Selection.ApplyPropertyValue(Run.TextDecorationsProperty, null);
                _isUnderlinedSelected = value;
                if (GetsFocusAfterFormattingChange)
                    this.Focus();
            }
        }

        /// <summary>
        /// Hex string representing the selected font colour in the format #AARRGGBB. If no text is selected, then it applies the formatting to the next text typed.
        /// </summary>
        public string FontColourSelectedHexString 
        {
            get
            {

                return _fontColourSelectedHexString;

            }
            set
            {
                Selection.ApplyPropertyValue(Run.ForegroundProperty, value);
                _fontColourSelectedHexString = value;
                if (GetsFocusAfterFormattingChange)
                    this.Focus();
            }
        }

        double _fontSizeSelected;

        /// <summary>
        /// The fontsize of the selected text. If no text is selected, then it applies the formatting to the next text typed.
        /// </summary>
        public double FontSizeSelected
        {
            get
            {
                return _fontSizeSelected;
            }
            set
            {
                Selection.ApplyPropertyValue(Run.FontSizeProperty, value);
                _fontSizeSelected = value;
                if (GetsFocusAfterFormattingChange)
                    this.Focus();
            }
        }

        FontFamily _fontFamilySelected;

        /// <summary>
        /// The FontFamily of the selected text. If no text is selected, then it applies the formatting to the next text typed.
        /// </summary>
        public FontFamily FontFamilySelected
        {
            get
            {
                return _fontFamilySelected;
            }
            set
            {
                Selection.ApplyPropertyValue(Run.FontFamilyProperty, value);
                _fontFamilySelected = value;
                if (GetsFocusAfterFormattingChange)
                    this.Focus();
            }
        }
        
    
        #region InotifyPropertyChanged Implementation

        /// <summary>
        /// Implements InotifyPropertyChanged.
        /// </summary>
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Implements InotifyPropertyChanged.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}
